<template>
  <div class="container">
    <div class="login-panel">
      <n-card embedded :bordered="false">
        <n-tabs animated default-value="login" size="large">
          <n-tab-pane name="login" tab="登 录">
            <n-form>
              <n-space vertical :size="18">
                <n-input placeholder="用户名" v-model:value="loginForm.username">
                  <template #prefix>
                    <n-icon :component="IconUser" />
                  </template>
                </n-input>
                <n-input
                    type="password"
                    show-password-on="click"
                    placeholder="密码"
                    v-model:value="loginForm.password"
                    @keyup.enter="login"
                >
                  <template #prefix>
                    <n-icon :component="IconLock" />
                  </template>
                </n-input>
                <n-button type="primary" block secondary strong
                          @click="login" :loading="loginRequesting" :disabled="loginRequesting">登 录</n-button>
              </n-space>
            </n-form>
          </n-tab-pane>
          <n-tab-pane name="register" tab="注 册">
            <n-form>
              <n-space vertical :size="18">
                <n-select placeholder="用户类型"
                          v-model:value="registerForm.role"
                          :options="UserRole"
                />
                <n-input placeholder="用户名" v-model:value="registerForm.username">
                  <template #prefix>
                    <n-icon :component="IconUser" />
                  </template>
                </n-input>
                <n-input
                    type="password"
                    show-password-on="click"
                    placeholder="密码"
                    v-model:value="registerForm.password"
                >
                  <template #prefix>
                    <n-icon :component="IconLock" />
                  </template>
                </n-input>
                <n-input
                    type="password"
                    show-password-on="click"
                    placeholder="重复密码"
                    v-model:value="registerForm.confirm_password"
                    @keyup.enter="register"
                >
                  <template #prefix>
                    <n-icon :component="IconLock" />
                  </template>
                </n-input>
                <n-button type="primary" block secondary strong
                          @click="register" :loading="registerRequesting" :disabled="registerRequesting">注 册</n-button>
              </n-space>
            </n-form>
          </n-tab-pane>
        </n-tabs>

        <div class="footer">
          <p class="tips">
            登录和注册即代表您已阅读并同意
            <n-a class="link" href="#">用户协议</n-a>。
          </p>
          <p class="tips">
            本网站受reCAPTCHA保护，适用谷歌
            <n-a class="link" href="https://policies.google.com/privacy" target="_blank">隐私政策</n-a>
            和
            <n-a class="link" href="https://policies.google.com/terms" target="_blank">服务条款</n-a>。
          </p>
        </div>
      </n-card>
    </div>
  </div>
</template>

<script>
import {ref, reactive} from "vue";
import {useMessage, useNotification} from 'naive-ui'
import {useRequests} from "@/common/requests";
import {useReCaptcha} from "@/common/reCaptcha";
import UserRole from "@/common/UserRole";
import IconUser from '@/components/icons/IconUser.vue'
import IconLock from '@/components/icons/IconLock.vue'
import {useRouter} from "vue-router";
import {useUserStore} from "@/stores/user";

export default {
  name: "LoginView",
  setup() {
    const router = useRouter()
    const message = useMessage()
    const notify = useNotification()
    const requests = useRequests()
    const reCaptcha = useReCaptcha()
    const userStore = useUserStore()

    const initData = {
      login() {
        return {
          username: '',
          password: '',
          captcha: null
        }
      },
      register() {
        return {
          role: UserRole[0].value,
          username: '',
          password: '',
          confirm_password: '',
          captcha: null
        }
      }
    }

    let loginForm = ref(initData.login())
    let registerForm = ref(initData.register())
    const loginRequesting = ref(false)
    const registerRequesting = ref(false)

    const login = () => {
      if (loginForm.value.username.length === 0) {
        message.error('请输入用户名')
      } else if (loginForm.value.password.length === 0) {
        message.error('请输入密码')
      } else {
        loginRequesting.value = true
        // 请求reCAPTCHA获得验证字符串
        reCaptcha(token => {
          loginForm.value.captcha = token

          requests.user.login(loginForm.value).then(resp => {
            loginRequesting.value = false
            if (resp.ret === 0) {
              userStore.$patch({token: resp.data, username: loginForm.value.username})

              loginForm.value = initData.login()
              message.success("登录成功")

              requests.profile.getMe().then(resp => {
                if (resp.ret === 0) {
                  userStore.$patch({profile: resp.data})
                }
              })
              requests.user.meta().then(resp => {
                if (resp.ret === 0) {
                  userStore.$patch({
                    role: resp.data.role,
                    status: resp.data.status
                  })
                }
              })

              router.back()
            } else {
              message.error(resp?.data ?? resp?.msg ?? '未知错误')
            }
          }).catch(err => {
            loginRequesting.value = false

            console.log(err)
            message.error('网络错误')
          })
        })
      }
    }

    const register = () => {
      if (registerForm.value.role < 0 || registerForm.value.role > UserRole.length - 1) {
        message.error('用户类型有误')
      } else if (registerForm.value.username.length === 0) {
        message.error('请输入用户名')
      } else if (registerForm.value.password.length === 0) {
        message.error('请输入密码')
      } else if (registerForm.value.confirm_password.length === 0) {
        message.error('请输入重复密码')
      } else if (registerForm.value.password !== registerForm.value.confirm_password) {
        message.error('两次输入的密码不一致')
      } else {
        registerRequesting.value = true
        // 请求reCAPTCHA获得验证字符串
        reCaptcha(token => {
          registerForm.value.captcha = token

          requests.user.register(registerForm.value).then(resp => {
            registerRequesting.value = false
            if (resp.ret === 0) {
              registerForm.value = initData.register()
              message.success("注册成功")
            } else {
              message.error(resp?.data ?? resp?.msg ?? '未知错误')
            }
          }).catch(err => {
            registerRequesting.value = false

            console.log(err)
            message.error('网络错误')
          })
        })
      }
    }

    return {
      IconUser,
      IconLock,
      UserRole,
      loginForm,
      loginRequesting,
      registerForm,
      registerRequesting,
      login,
      register,
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  height: calc(100vh - 48px);
  box-sizing: border-box;
  display: flex;
  align-items: center;

  .login-panel {
    flex: 1;
    max-width: 450px;
    margin: 0 auto;

    .footer {
      margin-top: 2rem;

      .tips, .tips .link {
        font-size: .7rem;
      }
    }
  }
}
</style>
